/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package CLIENT;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This class listenes to new messages from the server and sends them to the client
 * (A Thread Class)
 * @author Yaniv Kalif
 */
public class ClientMessageListener implements Runnable
{
    ClientConnection _connection;
   //BufferedReader in=null;
    ObjectInputStream in = null;
    ClientMainChatPanel _CreatorP;
    Client _client;
    public ClientMessageListener(ClientConnection connection,ClientMainChatPanel Creator) throws IOException
    {
        _connection = connection;
        //in = new BufferedReader(new InputStreamReader(_connection.GetConnectedSocket().getInputStream()));
        _CreatorP=Creator;
    }
    public void run()
    {
        try 
        {
            in = new ObjectInputStream(_connection.GetConnectedSocket().getInputStream());
            String msg = null;
            Message m = null;
            System.out.println("client Accept");
            /*
            while ((msg = in.readLine()) != null)
            {
                if(in != null)
                {
                    System.out.println("server:" + msg);
                    _CreatorP.RecieveMessage(msg);// send the message to all the users
                }
            }*/
            while ((m = (Message) in.readObject()) != null)
            {
                //Thread.sleep(500);
                //msg = (String) in.readObject();

                if(in != null)
                {
                    System.out.println("server:" + m);
                    if (m.GetisSystemMessage())
                    {
                        _client=_CreatorP.GetClient();
                        _client.SetID(Integer.valueOf(m.GetString()));
                        _connection.SendID(_client, String.valueOf(_client.GetID())); //send this name to the server
                    }
                    else
                        _CreatorP.RecieveMessage(m);// send the message to all the users
                    //_CreatorP.RecieveMessage(m.GetString());// send the message to all the users
                }
                //msg=null;
            }
        }
        catch (ClassNotFoundException ex)
        {
            Logger.getLogger(ClientMessageListener.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex)
        {
            Logger.getLogger(ClientMessageListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
